package com.sky.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * websocket服务端
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

//    存放会话对象
    private static Map<String, Session> sessionMap=new HashMap<>();

    /*
     * @Description  连接建立成功调用的方法
     * @Param [message, sid]
     * @return void
     **/
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        System.out.println("客户端：" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    /*
     * @Description  收到客户端消息后调用的方法
     * @Param [message, sid]
     * @return void
     **/
    @OnMessage
    public void onMessage(String message,@PathParam("sid") String sid){
        System.out.println("收到客户端：" + sid + "的消息：" + message);
    }

    /*
     * @Description  连接关闭调用的方法
     * @Param [sid]
     * @return void
     **/
    @OnClose
    public void onClose(@PathParam("sid") String sid){
        System.out.println("客户端：" + sid + "关闭连接");
        sessionMap.remove(sid);
    }

    /*
     * @Description  发送消息给所有客户端
     * @Param [message]
     * @return void
     **/
    public void sendToAllClient(String message){
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
